<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { ElDialog, ElButton, ElMessage } from 'element-plus';
import SimpleKeyboard from '#/components/simple-keyboard.vue';
import Keyboard from '#/assets/images/keyboard.svg';
import Verify from '#/assets/images/verifyPass.svg';
import { $t } from '@vben/locales';

interface Props {
  visible?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  visible: false
});

const emit = defineEmits<{
  'update:visible': [visible: boolean];
  close: [];
  returnToExam: [isDebugingNormal: boolean];
}>();

defineOptions({
  name: 'KeyboardDebugModal',
});

// 步骤状态类型
type StepStatus = 'initial' | 'active' | 'success' | 'error';

// 步骤数据
const steps = ref([
  { id: 1, title: $t('examCore.keyboardDebug'), status: 'initial' as StepStatus },
  { id: 2, title: $t('examCore.complete'), status: 'initial' as StepStatus }
]);
const normal = 'normal'
const currentStep = ref(1);
const debugStatus = ref<'testing' | 'normal' | 'error'>('testing');

// 键盘测试相关状态
const targetKeys = ['W', 'A', 'S', 'D'];
const currentIndex = ref(0);
const pressedKeys = ref<string[]>([]);
const isDebugging = ref(false);
const currentKey = ref('');

// 更新步骤状态
const updateStepStatus = (stepId: number, status: StepStatus, title?: string) => {
  const step = steps.value.find(s => s.id === stepId);
  if (step) {
    step.status = status;
    title && (step.title = title);
  }
};

// 处理键盘按键事件
const handleKeyPress = (key: string) => {
  if (!isDebugging.value) return;
  const expectedKey = targetKeys[currentIndex.value];
  if (key === expectedKey) {
    // 按对了键
    pressedKeys.value.push(key);
    currentIndex.value++;

    // 更新当前需要按的键
    if (currentIndex.value < targetKeys.length) {
      currentKey.value = targetKeys[currentIndex.value] || '';
    } else {
      // 完成所有按键
      currentKey.value = '';
      isDebugging.value = false;
      debugSuccess();
      debugStatus.value = normal;
    }
  } else {
    // 按错了键
    console.log($t('examCore.keyboardDebugOptions.wrongKeyPressed', { expected: expectedKey, actual: key }));
    debugError();
    debugStatus.value = 'error';
    isDebugging.value = true;
  }
};

// 开始调试
const startDebug = () => {
  updateStepStatus(1, 'active');
  currentStep.value = 1;
  isDebugging.value = true;
  currentIndex.value = 0;
  pressedKeys.value = [];
  currentKey.value = targetKeys[0] || '';
  debugStatus.value = 'testing';
};

// 调试成功
const debugSuccess = () => {
  updateStepStatus(1, 'success');
  updateStepStatus(2, 'success',$t('examCore.complete'));
  currentStep.value = 2;
};

// 调试失败
const debugError = () => {
  updateStepStatus(1, 'error');
  updateStepStatus(2, 'error', $t('examCore.incomplete'));
  currentStep.value = 2;
  isDebugging.value = false;
};

// 重置所有状态到初始状态
const resetAllState = () => {
  steps.value.forEach(step => {
    step.status = 'initial';
  });
  steps.value[1] && (steps.value[1].title = $t('examCore.complete'));
  currentStep.value = 1;
  isDebugging.value = false;
  currentIndex.value = 0;
  pressedKeys.value = [];
  currentKey.value = '';
  debugStatus.value = 'testing';
};

// 重新开始
const restart = () => {
  resetAllState();
};

// 返回考试
const returnToExam = () => {
  if (isDebugingNormal.value) {
    emit('returnToExam', isDebugingNormal.value);
    handleClose();
  } else {
    ElMessage.error($t('examCore.keyboardDebugRequired'));
  }
};

// 关闭弹窗
const handleClose = () => {
  emit('update:visible', false);
  emit('close');
};

// 监听弹窗显示状态
watch(() => props.visible, (newVisible, oldVisible) => {
  if (newVisible && !oldVisible) {
    // 弹窗刚打开时，总是重置到初始状态
    resetAllState();
  }
});

// 获取调试状态文字
const getStatusText = computed(() => {
  switch (debugStatus.value) {
    case 'testing':
      return 'W A S D';
    case normal:
      emit('returnToExam', isDebugingNormal.value);
      return $t('examCore.normal');
    case 'error':
      isDebugging.value = true;
      return $t('examCore.abnormal');
    default:
      return 'W A S D';
  }
});
const isDebugingNormal = computed(() => {
  return debugStatus.value === normal
})

// 获取状态颜色
const getStatusColor = computed(() => {
  switch (debugStatus.value) {
    case 'testing':
      return 'text-blue-600';
    case normal:
      return 'text-green-800';
    case 'error':
      return 'text-red-500';
    default:
      return 'text-green-800';
  }
});
</script>

<template>
  <el-dialog :model-value="visible" :close-on-click-modal="false" @update:model-value="emit('update:visible', $event)"
    :title="$t('examCore.keyboardDebug')" width="1000px" :before-close="handleClose">
    <!-- 步骤条 -->
    <div class="flex justify-center mb-7 mt-3">
      <div class="flex items-center">
        <div v-for="(step, index) in steps" :key="step.id" class="flex items-center">
          <div class="flex items-center gap-3">
            <!-- 步骤圆圈 -->
            <div :class="[
              'w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium transition-all duration-300 relative z-10',
              {
                'bg-white border-2 border-gray-300 text-gray-600': step.status === 'initial',
                'bg-[var(--el-color-primary)] border-2 border-[var(--el-color-primary)] text-white': step.status === 'active' || step.status === 'success',
                'bg-red-500 border-2 border-red-500 text-white': step.status === 'error'
              }
            ]">
              <!-- 初始状态和激活状态显示数字 -->
              <span v-if="step.status === 'initial' || step.status === 'active'" class="text-sm font-medium">
                {{ step.id }}
              </span>
              <!-- 成功状态显示勾选 -->
              <svg v-else-if="step.status === 'success'" class="w-4 h-4" viewBox="0 0 24 24" fill="none"
                stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
              </svg>
              <!-- 错误状态显示数字 -->
              <span v-else-if="step.status === 'error'" class="text-sm font-medium">
                {{ step.id }}
              </span>
            </div>

            <!-- 步骤标题 -->
            <div :class="[
              'text-sm transition-all duration-300 whitespace-nowrap',
              {
                'text-gray-600': step.status === 'initial',
                'text-[#0067D1] font-medium': step.status === 'active' || step.status === 'success',
                'text-red-500 font-medium': step.status === 'error'
              }
            ]">
              {{ step.title }}
            </div>
          </div>

          <!-- 连接线 -->
          <div v-if="index < steps.length - 1" :class="[
            'w-30 h-0.5 mx-4 transition-all duration-300',
            {
              'bg-blue-500': step.status === 'success',
              'bg-gray-300': step.status !== 'success'
            }
          ]"></div>
        </div>
      </div>
    </div>
    <div class="flex justify-start">
      <div class="flex gap-1 flex-wrap">
        <el-button type="primary" @click="startDebug" :disabled="isDebugging" class="px-4 py-2">
          {{ $t('examCore.keyboardDebugOptions.startDebug') }}
        </el-button>
        <el-button @click="restart" :disabled="!isDebugging && currentStep === 1" class="px-4 py-2">
          {{ $t('examCore.keyboardDebugOptions.restart') }}
        </el-button>
      </div>
    </div>
    <!-- 主要内容区域 -->
    <div class="flex justify-between pt-3 pb-9">
      <!-- 左侧：虚拟键盘 -->
      <SimpleKeyboard class="flex-1" :current-key="currentKey" :pressed-keys="pressedKeys" :is-active="isDebugging"
        @key-press="handleKeyPress" />

      <!-- 右侧：调试状态和控制区域 -->
      <div class="w-[380px] ml-6">
        <!-- 调试状态显示 -->
        <div class="mb-2">
          <div class="mb-4">
            <span class="text-gray-600 text-sm">{{ $t('examCore.keyboardDebugOptions.debugStatus') }}</span>
            <span :class="['ml-4', getStatusColor]">
              {{ getStatusText }}
            </span>
          </div>

          <!-- 当前按键提示 -->
          <div v-if="isDebugging && currentKey" class="mb-4 p-3 bg-blue-50 border border-blue-200 rounded">
            <div class="text-sm text-blue-600 mb-1">{{ $t('examCore.keyboardDebugOptions.pleasePress') }}</div>
            <div class="text-2xl font-bold text-blue-800">{{ currentKey }}</div>
            <div class="text-xs text-blue-500 mt-1">{{ $t('examCore.keyboardDebugOptions.progress') }}{{ currentIndex }}/{{ targetKeys.length }}</div>
          </div>

          <!-- 已按过的键显示 -->
          <div v-if="pressedKeys.length > 0" class="mb-4">
            <div class="text-sm text-gray-600 mb-1">{{ $t('examCore.keyboardDebugOptions.pressedKeys') }}</div>
            <div class="flex gap-1">
              <span v-for="key in pressedKeys" :key="key" class="px-2 py-1 bg-green-100 text-green-800 text-sm rounded">
                {{ key }}
              </span>
            </div>
          </div>
          <!-- 返回考试按钮 -->
          <div class="flex flex-col items-center justify-center">
            <img :src="isDebugingNormal ? Verify : Keyboard" alt="keyboard" class="w-[78px] pb-[17px]" />
            <el-button type="primary" @click="returnToExam" class="w-[200px]">
              {{ $t('examCore.returnToExam') }}
            </el-button>
          </div>
        </div>

        <!-- 注意事项 -->
        <div class="text-gray-600 space-y-2">
          <div class="font-medium">{{ $t('common.tipTxt') }}：</div>
          <div class="text-[12px]">{{ $t('examCore.keyboardDebugOptions.instruction1') }}</div>
          <div class="text-[12px]">{{ $t('examCore.keyboardDebugOptions.instruction2') }}</div>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<style scoped>
/* 自定义连接线宽度 */
.w-30 {
  width: 7.5rem;
}
</style>
